package com.springboot2.controller;

import com.springboot2.entity.Goods;
import com.springboot2.service.GoodsService;
import com.springboot2.utils.Result;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("goods/")
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    //增
    @PostMapping("add")
    public Result add(@RequestBody Goods goods){
        goodsService.add(goods);
        return Result.success();
    }
    //删
    @DeleteMapping("del/{id}")
    public Result del(@PathVariable int id){
        goodsService.del(id);
        return Result.success();
    }
    //改
    @PutMapping("update")
    public Result update(@RequestBody Goods goods){
        goodsService.update(goods);
        return Result.success();
    }
    //获取对象
    @GetMapping("findById/{id}")
    public Result findById(@PathVariable int id){
        return Result.success(goodsService.findById(id));
    }
    //分页列表
    @GetMapping("findByPage/{pageNo}/{pageSize}")
    public Result findByPage(@PathVariable int pageNo,@PathVariable int pageSize){
        Map<String,Object> map = new HashMap<>();
        map.put("data",goodsService.findByPage(pageNo, pageSize));
        map.put("total", goodsService.count());
        return Result.success(map);
    }
    //查询条件
    @GetMapping("findByPageParams/{pageNo}/{pageSize}/{title}")
    public Result findByPageParams(@PathVariable int pageNo,@PathVariable int pageSize,@PathVariable String title){
        Map<String,Object> map = new HashMap<>();
        map.put("data",goodsService.findByPageParams(pageNo, pageSize, title));
        map.put("total",goodsService.countParams());
        return Result.success(map);
    }

    //删
    @DeleteMapping("batch/{ids}")
    @Transactional
    public Result batch(@PathVariable String ids){
       String [] splits = ids.split(",");
       for(String id: splits){
           goodsService.del(Integer.parseInt(id));
       }
        return Result.success();
    }

}
